package com.avic.rong.userOrder.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseFragment;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.userOrder.activity.MineOrderActivity;
import com.avic.rong.userOrder.adapter.MineOrderListAdapter;
import com.avic.rong.userOrder.api.OrderListApi;
import com.avic.rong.userOrder.bean.AllOrderListBean;
import com.avic.rong.userOrder.event.CourseJumpEvent;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineOrderFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {


    @BindView(R.id.order_list)
    RecyclerView orderListRecy;

    private LoadingLayout loading_layout;
    Unbinder unbinder;
    private MineOrderListAdapter mineOrderListAdapter;

    private String type;
    private List<AllOrderListBean.OrderListBean> listData = new ArrayList<>();

    SmartRefreshLayout refreshLayout;
    private String orderType;

    //列表更新
    private int LIST_UPDATE = 1000;

    private TextView tv_goods_bug;

    private LinearLayout ll_order_no_data;

    @Override
    protected void initView() {
        refreshLayout = fragmentView.findViewById(R.id.refreshLayout);
        loading_layout = fragmentView.findViewById(R.id.loading_layout);
        ll_order_no_data = fragmentView.findViewById(R.id.ll_order_no_data);
        tv_goods_bug = fragmentView.findViewById(R.id.tv_goods_bug);

        EventBus.getDefault().register(this);
        Bundle arguments = getArguments();
        type = (String) arguments.get("ORDER_TYPE");
        if (TextUtils.isEmpty(type)) {
            return;
        }
        loading_layout.setStatus(LoadingLayout.LOADING);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        orderListRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        mineOrderListAdapter = new MineOrderListAdapter(context, listData);
        orderListRecy.setAdapter(mineOrderListAdapter);


        initData(orderType);


    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
       /* if(isVisibleToUser){
            if (TextUtils.isEmpty(type))return;
            initData(orderType);
        }*/
    }

    private void initData(String orderType) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            //订单类型0：全部、1：软件、2：元器件、4：标准、5：培训、8：会员服务
            if (TextUtils.isEmpty(orderType)) {
                map.put("orderType", "0");
            } else {
                if (orderType.equals("全部")) {
                    map.put("orderType", "0");
                } else if (orderType.equals("软件服务")) {
                    map.put("orderType", "1");
                } else if (orderType.equals("标准")) {
                    map.put("orderType", "4");
                } else if (orderType.equals("元器件")) {
                    map.put("orderType", "2");
                } else if (orderType.equals("培训")) {
                    map.put("orderType", "5");
                } else if (orderType.equals("会员服务")) {
                    map.put("orderType", "8");
                }
            }


            if (type.equals("全部")) {
                map.put("type", "0");
            } else if (type.equals("待付款")) {
                map.put("type", "1");
            } else if (type.equals("待发货")) {
                map.put("type", "2");
            } else if (type.equals("待收货")) {
                map.put("type", "3");
            } else if (type.equals("交易完成")) {
                map.put("type", "4");
            }
            map.put("pageNo", currentPageNumber + "");
            map.put("pageSize", "5");
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            //配送方式列表
            final OrderListApi orderListApi = new OrderListApi((RxAppCompatActivity) getActivity(), simpleOnNextListener);
            orderListApi.setCache(false);
            orderListApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderListApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(orderListApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    getActivity().onBackPressed();
                }
            });
//            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    @Override
    protected void addListener() {
        tv_goods_bug.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(new GoCartListEvent());
                Intent intent = MainActivity.queryIntent(context);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_mine_order;
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        initData(orderType);

//        refreshLayout.finishLoadMore(2000);//传入false表示加载失败
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        isRefresh = true;
        currentPageNumber = 1;
        initData(orderType);
//        refreshLayout.finishRefresh(2000);//传入false表示刷新失败
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (isRefresh) {
                listData.clear();
            }

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(getContext(), subjects.getMsg());
                return;
            }
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            AllOrderListBean allOrderListBean = (AllOrderListBean) subjects.getData();
//            currentPageNumber = allOrderListBean.get();
            List<AllOrderListBean.OrderListBean> orderList = allOrderListBean.getOrderList();

            mineOrderListAdapter.setBiaoZhunImg(allOrderListBean.getBiaoZhunImg());
            ;
            mineOrderListAdapter.setFileServer(allOrderListBean.getFileServer());
            listData.addAll(orderList);
            if (listData != null && listData.size() <= 0) {
//                loading_layout.setStatus(LoadingLayout.EMPTY);
                ll_order_no_data.setVisibility(View.VISIBLE);
                orderListRecy.setVisibility(View.GONE);
            }else   if (listData != null && listData.size() > 0) {
                ll_order_no_data.setVisibility(View.GONE);
                orderListRecy.setVisibility(View.VISIBLE);
            }
            mineOrderListAdapter.notifyDataSetChanged();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    @Subscribe
    public void onEventShowThread(InformUpdate event) {
        if (event != null) {
            if (event.getEventType() == InformUpdate.CANCEL_ORDER_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.ORDER_COMMENT_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.SUBMIT_PROOF_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.DELETE_ORDER_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.CONFIRM_SHOUHUO_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.ORDER_TYPE_INFORM) {
                orderType = event.getOrderType();
                refreshLayout.autoRefresh();
//                ((MineOrderActivity) getContext()).orderStart();
            } else if (event.getEventType() == InformUpdate.ORDER_RECOVER_INFORM) {
                refreshLayout.autoRefresh();
                ((MineOrderActivity) getContext()).orderStart();
            }


        }
    }

    /**
     * 点击“订单列表返回”切换到我的fragment
     *
     * @param courseJumpEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void courseJump(CourseJumpEvent courseJumpEvent) {
        orderType = courseJumpEvent.getOrderType();
        refreshLayout.autoRefresh();
//        ((MineOrderActivity) getContext()).orderStart();

        EventBus.getDefault().removeStickyEvent(CourseJumpEvent.class);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LIST_UPDATE && resultCode == RESULT_OK) {
            refreshLayout.autoRefresh();
            ((MineOrderActivity) getContext()).orderStart();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }


}
